package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.behavior.entity.ApLikesBehavior;
import com.usian.behavior.mapper.ApLikesBehaviorMapper;
import com.usian.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.JsonUtils;
import com.usian.model.article.msg.ArticleBehaviorMsg;
import com.usian.model.behavior.dtos.LikesBehaviorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.usian.common.constants.message.HotArticleConstants.HOT_ARTICLE_SCORE_STREAM_TOPIC;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-14
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void like(LikesBehaviorDto dto) {
        //1、参数校验
        if(dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2、判断用户是否登录
        Boolean isUser=false;
        //从线程中获取用户信息
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId!=null){
            isUser=true;
        }

        //3、查询用户或者设备是否对当前文章进行过点赞
        QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApLikesBehavior::getArticleId,dto.getArticleId());
        if(isUser){
            //用户点赞行为
            queryWrapper.lambda().eq(ApLikesBehavior::getApUserId,userId);
        }else{
            //设备点赞
            queryWrapper.lambda().eq(ApLikesBehavior::getEquipmentId,dto.getEquipmentId());
        }
        ApLikesBehavior likesBehavior = this.getOne(queryWrapper);
        if(likesBehavior==null){
            //4、如果没有点赞，记录点赞行为
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setArticleId(dto.getArticleId());
            if(isUser){
                likesBehavior.setApUserId(userId);
            }else{
                likesBehavior.setEquipmentId(dto.getEquipmentId());
            }
            likesBehavior.setType(dto.getType());
            likesBehavior.setCreatedTime(new Date());
            boolean b = this.save(likesBehavior);
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存点赞行为失败");
            }
        }else{
            //5、如果点赞过，更新点赞为取消点赞，并记录修改时间
            likesBehavior.setOperation(dto.getOperation());
            likesBehavior.setUpdateTime(new Date());
            boolean b = this.updateById(likesBehavior);
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新点赞行为失败");
            }
        }

        //点赞行为，生产一条消息
        if(dto.getOperation()==1){
            ArticleBehaviorMsg articleBehaviorMsg = new ArticleBehaviorMsg(dto.getArticleId(),1, ArticleBehaviorMsg.ArticleBehaviorType.LIKES);
            kafkaTemplate.send(HOT_ARTICLE_SCORE_STREAM_TOPIC, JsonUtils.toString(articleBehaviorMsg));
        }

    }

    @Override
    public ApLikesBehavior findLikeByArticleId(Integer userId, String equipmentId, Long articleId, Integer likeType) {
        //判断是用户还是设备操作
        Boolean isUser=false;
        if(userId!=null && userId!=0){
            //用户操作
            isUser=true;
        }
        //封装查询条件
        QueryWrapper<ApLikesBehavior> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApLikesBehavior::getArticleId,articleId).eq(ApLikesBehavior::getType,likeType);
        if(isUser){
            //用户操作
            queryWrapper.lambda().eq(ApLikesBehavior::getApUserId,userId);
        }else{
            //设备操作
            queryWrapper.lambda().eq(ApLikesBehavior::getEquipmentId,equipmentId);
        }

        ApLikesBehavior likesBehavior = this.getOne(queryWrapper);
        return likesBehavior;
    }
}
